class_name Unit
extends Area2D


@onready var visuals: UnitVisuals = $Visuals
@onready var sprite: Sprite2D = $Visuals/Sprite
@onready var health_bar: HealthBar = $HealthBar
@onready var collision_shape: CollisionShape2D = $CollisionShape2D
@onready var animation_player: AnimationPlayer = $AnimationPlayer
@onready var health_component: HealthComponent = $HealthComponent
@onready var hurtbox_component: HurtboxComponent = $HurtboxComponent
@onready var state_machine: NodeStateMachine = $StateMachine


@export var stats: UnitStats



func _ready():
	hurtbox_component.damage_hitbox.connect(_on_damage_hitbox)
	health_component.health_change.connect(_on_health_changed)

	health_component.setup(stats)




func _on_damage_hitbox(hitbox: HitboxComponent):
	if health_component.current_health == 0:
		return

	var blocked := Sundry.success_chance(stats.block_chance)
	if blocked:
		on_blocked(hitbox)
		PlayManager.damage_block.emit(self, hitbox)
		return

	health_component.take_damage(hitbox.damage)
	on_damage(hitbox)
	PlayManager.damage_hurt.emit(self, hitbox)


func _on_health_changed(current_value: int, max_value: int):
	health_bar.set_value(current_value, max_value)



## 受到伤害时被调用，重写此方法可用于处理受伤的效果
func on_damage(hitbox: HitboxComponent):
	prints("=== on_damage:", hitbox.name, hitbox.source)


## 格挡伤害，重写此方法可用于处理格挡效果
func on_blocked(hitbox: HitboxComponent):
	prints("=== on_blocked", hitbox.name, hitbox.source)
	pass
